<template>
    <div class="container">
        <h2 class="title">编辑权限</h2>
        <el-form ref="permissionFormRef" :model="permissionForm" :rules="rules" label-width="120px"
            class="permission-form">
            <el-form-item label="权限名称：" prop="permissonName">
                <el-input v-model="permissionForm.permissonName" placeholder="请输入权限名称" />
            </el-form-item>

            <el-form-item label="权限URL：" prop="permissonValue">
                <el-input v-model="permissionForm.permissonValue" placeholder="请输入权限URL" />
            </el-form-item>

            <!-- <el-form-item label="权限序号：" prop="permissionCode">
          <el-input v-model.number="permissionForm.permissionCode" type="number" placeholder="请输入权限序号" />
        </el-form-item>
         -->
            <!-- <el-form-item label="权限类型：" prop="permissionType">
                <el-cascader v-model="permissionForm.perseId" :options="permissionTypeOptions" placeholder="请选择权限类型"
                    :props="cascaderProps" />
            </el-form-item> -->


        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const route = useRoute()
const router = useRouter()
import { Check, ArrowLeft } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/counter'
import { read, write } from '@/Until/axiosHepler'
import axios from 'axios'


const stores = useCounterStore()
const permissionFormRef = ref<FormInstance>()
onMounted(() => {
    List()
})
let permissionId = route.query.permissonId

const List = () => {
    console.log('接收到的权限ID:', permissionId)

    if (!permissionId) {
        ElMessage.warning('缺少权限ID参数')
        return
    }

    read.get("/api/User/PermissonDetail", { params: { PermissonId: permissionId } })
        .then((res) => {
            console.log('API响应:', res.data)
            if (res.data.code == 200) {
                permissionForm.permissonName = res.data.data.permissonName
                 permissionForm.permissonValue = res.data.data.permissonValue
                  permissionForm.perseId = res.data.data.perseId
            }
            else {
                ElMessage.error('失败');
            }
            // if (res.data && res.data.code === 200 && res.data.data) {
            //     permissionForm.permissonName = res.data.data.permissonName || ''
            //     permissionForm.permissonValue = res.data.data.permissonValue || ''
            //     // 将数字转换为级联选择器需要的数组格式
            //     permissionForm.perseId = res.data.data.perseId ? [res.data.data.perseId] : []
            //     ElMessage.success('权限详情加载成功')
            // } else if (res.data && res.data.code === 0 && !res.data.data) {
            //     ElMessage.warning('该权限不存在或已被删除')
            // } else {
            //     ElMessage.error(res.data.message || '获取权限详情失败：数据格式错误')
            // }
        })
        .catch((error) => {
            console.error('获取权限详情出错:', error)
            ElMessage.error('获取权限详情失败')
        })
}

// 权限类型选项数据
const permissionTypeOptions = [
    {
        value: 'menu',
        label: '菜单权限',
        children: [
            { value: 'main_menu', label: '主菜单' },
            { value: 'sub_menu', label: '子菜单' },
            { value: 'hidden_menu', label: '隐藏菜单' }
        ]
    },
    {
        value: 'operation',
        label: '操作权限',
        children: [
            { value: 'create', label: '创建' },
            { value: 'read', label: '查看' },
            { value: 'update', label: '修改' },
            { value: 'delete', label: '删除' }
        ]
    },
    {
        value: 'data',
        label: '数据权限',
        children: [
            { value: 'own', label: '本人数据' },
            { value: 'dept', label: '部门数据' },
            { value: 'all', label: '全部数据' }
        ]
    }
]

// 级联选择器配置
const cascaderProps = {
    value: 'value',
    label: 'label',
    children: 'children',
    expandTrigger: 'hover'
}

// 权限表单数据类型定义
interface PermissionForm {
    "permissonName": string,
    "permissonValue": string,
    "perseId": any[]
}

// 初始化表单数据
const permissionForm = reactive<PermissionForm>({
    "permissonName": "",
    "permissonValue": "",
    "perseId": []
})

// 表单验证规则
const rules = reactive<FormRules<PermissionForm>>({
    permissonName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { max: 50, message: '权限名称不能超过50个字符', trigger: 'blur' }
    ],
    permissonValue: [
        { required: true, message: '请输入权限URL', trigger: 'blur' },
        { max: 200, message: '权限URL不能超过200个字符', trigger: 'blur' }
    ],

    perseId: [
        {
            required: true,
            message: '请选择权限类型',
            trigger: 'change',
            type: 'array'
        }
    ]
})

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid, fields) => {
        if (valid) {
            // 模拟提交数据到后端
            savePermission().then(() => {
                write.post("api/Permission/AddPermission", permissionForm).then((res) => {
                    if (res.data.code === 200) {
                        ElMessage.success('权限添加成功！')
                    } else {
                        ElMessage.error('权限添加失败：' + res.data.message)
                    }
                })
                // 重置表单
                resetForm()
                // 可以选择跳转或其他操作
            }).catch(error => {
                ElMessage.error('权限添加失败：' + error.message)
            })
        } else {
            console.log('表单验证失败', fields)
        }
    })
}

// 保存权限的API调用
const savePermission = async () => {
    try {
        // 根据实际API调整请求URL和参数
        const response = await read.post('/api/Permission/AddPermission', permissionForm)

        if (response.data.code === 200) {
            return response.data
        } else {
            throw new Error(response.data.message || '添加权限失败')
        }
    } catch (error) {
        console.error('保存权限出错:', error)
        throw error
    }
}

// 重置表单
const resetForm = () => {
    permissionForm.permissonName = ''
    permissionForm.permissonValue = ''
    permissionForm.perseId = []


    if (permissionFormRef.value) {
        permissionFormRef.value.resetFields()
    }
}

// 返回上一页
const handleBack = () => {
    router.back()
}
</script>

<style scoped>
.container {
    width: 100%;
    max-width: 600px;
    margin: 0 auto;
    padding: 40px 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 50px;
}

.title {
    text-align: center;
    margin-bottom: 30px;
    color: #303133;
    font-size: 24px;
    font-weight: 500;
}

.permission-form {
    width: 100%;
}

.form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 40px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-input__wrapper) {
    border-radius: 4px;
}

:deep(.el-button) {
    min-width: 100px;
}
</style>